function bucketSort(arr, bucketSize=3){
	if(arr.length <= bucketSize){
		return insertSort(arr)
	}
	const max = Math.max(...arr)
	const min = Math.min(...arr)
	const bucketCount = Math.floor((max - min) / bucketSize) + 1
	const buckets = Array.from({length: bucketCount}, ()=>[])

	for(let i = 0; i<arr.length; i++){
		const bucketIndex = Math.floor((arr[i] - min) / bucketSize)
		buckets[bucketIndex].push(arr[i])
	}

	arr.length = 0
	for(let i=0;i<buckets.length;i++){
		insertSort(buckets[i])
		arr.push(...buckets[i])
	}
	return arr
}

function insertSort(arr){
	const n = arr.length
	for(let i=1;i<n;i++){
		const pivot = arr[i]
		let j = i - 1
		while( j>=0 && arr[j]>pivot ){
			arr[j+1] = arr[j]
			j--
		}
		arr[j + 1] = pivot
	}
	return arr 
}

const arr = [1, 3, 5, 7, 2, 4, 6, 8];
console.log(bucketSort(arr))